<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class scratchcard extends template_plugin
{
	var $ipsclass;
	
	var $name = "Scratchcard";
	var $multiple = 0;
	var $cache_array = array('ibm_scratchcard' => array('Scratchcard card cache','scratchcard_cache'));
	
	function scratchcard_cache()
	{
		$this->ipsclass->cache['ibm_scratchcard'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_scratchcard_card'));
		$this->ipsclass->DB->exec_query();
		while($card = $this->ipsclass->DB->fetch_row())
		{
			$card['choice_imgs'] = unserialize($card['choice_imgs']);
			$card['choice_info'] = unserialize($card['choice_info']);
			$card['prizes'] = unserialize($card['prizes']);
			$this->ipsclass->cache['ibm_scratchcard'][$card['sc_id']] = $card;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'ibm_scratchcard', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function load_gametype($gametype="")
	{
		$file = $gametype;
		if(is_array($gametype))
		{
			$file = $gametype['game_type'];
		}
		if(!file_exists(ROOT_PATH."sources/market/scratchcard/gametype_".$file.".php"))
		{
			return null;
		}
		if(!class_exists('gametype'))
		{
			require_once(ROOT_PATH."sources/market/scratchcard/gametype.php");
		}
		require_once(ROOT_PATH."sources/market/scratchcard/gametype_".$file.".php");
		$class = "gametype_".$file;
		$game = new $class;
		$game->ipsclass =& $this->ipsclass;
		if(is_array($gametype))
		{
			$game->card_info = $gametype;
		}
		return $game;
	}
	
	function acp_install()
	{
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
		
		$this->ipsclass->DB->build_query_from_cache('table_scratchcard_card',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_scratchcard_ticket',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		
		$this->scratchcard_cache();
	}
	
	function acp_uninstall()
	{
		$this->ipsclass->DB->sql_drop_table( 'market_scratchcard_card'   );
		$this->ipsclass->DB->sql_drop_table( 'market_scratchcard_ticket' );
	}
	
	function acp_menu()
	{
		return array(
					  1 => array('Manage Scratchcard','code=plugin&do=run&link='.$this->plugin['link'].'&action=manage'),
					  2 => array('View Tickets','code=plugin&do=run&link='.$this->plugin['link'].'&action=ticket'),
					);
	}
	
	function acp()
	{
		$redirect = array(
							'manage' => 'manage_scratchcard',
							'ticket' => 'view_ticket',
						);
		
		if(!isset($redirect[$this->ipsclass->input['action']]))
		{
			$this->ipsclass->input['action'] = 'manage';
		}
		
		$function = 'acp_'.$redirect[$this->ipsclass->input['action']];
		$this->$function();
	}
	
	function acp_manage_scratchcard()
	{
		$redirect = array(
								'list' => 'list',
								'form' => 'add_form',
								'add' => 'add_save',
								'edit' => 'edit_form',
								'save' => 'edit_save',
								'delete' => 'delete',
								'export' => 'export',
							);
		if(!$redirect[$this->ipsclass->input['runme']])
		{
			$this->ipsclass->input['runme'] = 'list';
		}
		
		$function = 'acp_scratchcard_'.$redirect[$this->ipsclass->input['runme']];
		$this->$function();
	}
	
	function acp_scratchcard_list()
	{
		$this->ipsclass->admin->page_title  = "Welcome to managing scratchcards";
		$this->ipsclass->admin->page_detail = "Welcome to managing scratchcards. Here you can add/edit/delete scratchcard.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code, 'Scratchcard List' );
		
		$this->ipsclass->adskin->td_header[] = array( "Image"            , "" );
		$this->ipsclass->adskin->td_header[] = array( "Name/Description" , "" );
		$this->ipsclass->adskin->td_header[] = array( "Price"            , "" );
		$this->ipsclass->adskin->td_header[] = array( "Edit/Delete"      , "" );
		if(IN_DEV == 1)
		{
			$this->ipsclass->adskin->td_header[] = array( "Export"       , "" );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Scratchcard List");
		
		if(is_array($this->ipsclass->cache['ibm_scratchcard']) and count($this->ipsclass->cache['ibm_scratchcard']))
		{
			foreach($this->ipsclass->cache['ibm_scratchcard'] as $c_id => $card)
			{
				$row = array(
								"<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$card['folder']."/".$card['card_img']."' width='".$card['size_width']."' height='".$card['size_height']."' />",
								"<b>".$card['name']."</b><br />".$card['description'],
								$this->ipsclass->vars['market_prefix'].$this->ipsclass->do_number_format($card['price']).$this->ipsclass->vars['market_suffix'],
								"<a href='".$this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=manage&amp;runme=edit&amp;card=".$c_id."'>Edit</a><br /><a href='".$this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=manage&amp;runme=delete&amp;card=".$c_id."'>Delete</a>",
							);
				if(IN_DEV == 1)
				{
					$row[] = "<a href='".$this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=manage&amp;runme=export&amp;card=".$c_id."'>Export</a>";
				}
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row($row);
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No scratchcard made yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		require_once( KERNEL_PATH.'class_xml.php' );
		$xml = new class_xml();
		
		$cards = array();
		$files = $this->ipsclass->market_class->get_file_list(ROOT_PATH."sources/market/scratchcard",0);
		foreach($files as $file)
		{
			if(strstr($file,'.xml') != '.xml')
			{
				continue;
			}
			$content = file_get_contents(ROOT_PATH."sources/market/scratchcard/".$file);
			if ( $content == FALSE )
			{
				continue;
			}
			
			$xml->xml_parse_document($content);
			if ( ! is_array( $xml->xml_array['scratchcardexport']['scratchcard']['card_info'] ) )
			{
				continue;
			}
			
			$cards[] = array($file,$xml->xml_array['scratchcardexport']['scratchcard']['card_info']['name']['VALUE']);
		}
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','manage'),
																	array('runme','form'),
														)	);
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Add a Scratchcard");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Which type of card?</b>",
																			  $this->ipsclass->adskin->form_dropdown("xml_file",$cards)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Add Scratchcard");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_scratchcard_add_form()
	{
		if(strstr($this->ipsclass->input['xml_file'],'.xml') != '.xml')
		{
			$this->ipsclass->admin->error("Cannot find that scratchcard");
		}
		if(!file_exists(ROOT_PATH."sources/market/scratchcard/".$this->ipsclass->input['xml_file']))
		{
			$this->ipsclass->admin->error("Cannot find that scratchcard");
		}
		$content = file_get_contents(ROOT_PATH."sources/market/scratchcard/".$this->ipsclass->input['xml_file']);
		if ( $content == FALSE )
		{
			$this->ipsclass->admin->error("Cannot find that scratchcard");
		}
		
		require_once( KERNEL_PATH.'class_xml.php' );
		$xml = new class_xml();
		$xml->xml_parse_document($content);
		if ( ! is_array( $xml->xml_array['scratchcardexport']['scratchcard']['card_info'] ) )
		{
			$this->ipsclass->admin->error("Cannot read scratchcard info");
		}
		
		$class = $this->load_gametype($xml->xml_array['scratchcardexport']['scratchcard']['card_info']['game_type']['VALUE']);
		$class->_xml_to_info($xml);
		
		$this->ipsclass->admin->page_title  = "Welcome to adding a scratchcard";
		$this->ipsclass->admin->page_detail = "Welcome to adding a scratchcard.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code, 'Scratchcard List' );
		$this->ipsclass->admin->nav[] 		= array( ''                        , 'Add Scratchcard'  );
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','manage'),
																	array('runme','add'),
																	array('xml_file',$this->ipsclass->input['xml_file']),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Add a Scratchcard");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name of this scratchcard</b>",
																			  $this->ipsclass->adskin->form_input('name',$class->card_info['name'])
																	 )      );
		
		$description = $class->card_info['description'];
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$description = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $description ) );
			$description = $this->ipsclass->parser->convert_ipb_html_to_html( $description );
		}
		else
		{
			$description = $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $description ) );
		}
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Description</b><br />".$this->ipsclass->han_editor->show_editor( $description, 'description' ), 'left', 'tablerow1');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Price for one ticket</b>",
																			  $this->ipsclass->vars['market_prefix'].$this->ipsclass->adskin->form_simple_input('price',$class->card_info['price']).$this->ipsclass->vars['market_suffix']
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Game Play</b>",
																			$class->name,
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Card Image</b>",
																			"<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$class->card_info['folder']."/".$class->card_info['card_img']."' width='".$class->card_info['size_width']."' height='".$class->card_info['size_height']."' />",
																	)	);
		
		if($class->card_info['empty_img'])
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>Unscratched Area Image</b>",
																				"<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$class->card_info['folder']."/".$class->card_info['empty_img']."' />",
																		)	);
		}
		
		$images = array();
		foreach($class->card_info['choice_imgs'] as $image)
		{
			$images[] = "<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$class->card_info['folder']."/".$image."' />";
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Area Images</b>",
																			implode(" ",$images),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		if($html = $class->admin_form())
		{
			$this->ipsclass->html .= $html;
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Add Scratchcard");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_scratchcard_add_save()
	{
		if(strstr($this->ipsclass->input['xml_file'],'.xml') != '.xml')
		{
			$this->ipsclass->admin->error("Cannot find that scratchcard");
		}
		if(!file_exists(ROOT_PATH."sources/market/scratchcard/".$this->ipsclass->input['xml_file']))
		{
			$this->ipsclass->admin->error("Cannot find that scratchcard");
		}
		$content = file_get_contents(ROOT_PATH."sources/market/scratchcard/".$this->ipsclass->input['xml_file']);
		if ( $content == FALSE )
		{
			$this->ipsclass->admin->error("Cannot find that scratchcard");
		}
		
		require_once( KERNEL_PATH.'class_xml.php' );
		$xml = new class_xml();
		$xml->xml_parse_document($content);
		if ( ! is_array( $xml->xml_array['scratchcardexport']['scratchcard']['card_info'] ) )
		{
			$this->ipsclass->admin->error("Cannot read scratchcard info");
		}
		
		$class = $this->load_gametype($xml->xml_array['scratchcardexport']['scratchcard']['card_info']['game_type']['VALUE']);
		$class->_xml_to_info($xml);
		
		$card = array(
						'folder' => $class->card_info['folder'],
						'size_width' => $class->card_info['size_width'],
						'size_height' => $class->card_info['size_height'],
						'card_img' => $class->card_info['card_img'],
						'empty_img' => $class->card_info['empty_img'],
						'game_type' => $class->card_info['game_type'],
						'choice_imgs' => $class->card_info['choice_imgs'],
						'choice_info' => $class->card_info['choice_info'],
						'name' => $this->ipsclass->input['name'],
						'description' => $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->han_editor->process_raw_post( 'description' ) ) ),
						'price' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['price'],'int'),
						'prizes' => array(),
					);
		
		$class->admin_save($card);
		
		$card['choice_imgs'] = serialize($card['choice_imgs']);
		$card['choice_info'] = serialize($card['choice_info']);
		$card['prizes'] = serialize($card['prizes']);
		$card['description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $card['description'] ) );
		
		$this->ipsclass->DB->do_insert('market_scratchcard_card',$card);
		
		$this->scratchcard_cache();
		
		$this->ipsclass->admin->save_log("ibMarket: Scratchcard Added");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Scratchcard added...");
	}
	
	function acp_scratchcard_edit_form()
	{
		$this->ipsclass->input['card'] = intval($this->ipsclass->input['card']);
		
		if(!is_array($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]))
		{
			$this->ipsclass->admin->error("Unknown scratchcard");
		}
		
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]);
		
		$this->ipsclass->admin->page_title  = "Welcome to editing a scratchcard";
		$this->ipsclass->admin->page_detail = "Welcome to editing a scratchcard.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code, 'Scratchcard List' );
		$this->ipsclass->admin->nav[] 		= array( ''                        , 'Edit Scratchcard'  );
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																array('action','manage'),
																array('runme','save'),
																array('card',$this->ipsclass->input['card']),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Edit Scratchcard");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name of this scratchcard</b>",
																			  $this->ipsclass->adskin->form_input('name',$class->card_info['name'])
																	 )      );
		
		$description = $class->card_info['description'];
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$description = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $description ) );
			$description = $this->ipsclass->parser->convert_ipb_html_to_html( $description );
		}
		else
		{
			$description = $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $description ) );
		}
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Description</b><br />".$this->ipsclass->han_editor->show_editor( $description, 'description' ), 'left', 'tablerow1');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Price for one ticket</b>",
																			  $this->ipsclass->vars['market_prefix'].$this->ipsclass->adskin->form_simple_input('price',$class->card_info['price']).$this->ipsclass->vars['market_suffix']
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Game Play</b>",
																			$class->name,
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Card Image</b>",
																			"<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$class->card_info['folder']."/".$class->card_info['card_img']."' width='".$class->card_info['size_width']."' height='".$class->card_info['size_height']."' />",
																	)	);
		
		if($class->card_info['empty_img'])
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>Unscratched Area Image</b>",
																				"<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$class->card_info['folder']."/".$class->card_info['empty_img']."' />",
																		)	);
		}
		
		$images = array();
		foreach($class->card_info['choice_imgs'] as $image)
		{
			$images[] = "<img src='".$this->ipsclass->market_class->image_url_path."/scratchcard/".$class->card_info['folder']."/".$image."' />";
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>Area Images</b>",
																			implode(" ",$images),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		if($html = $class->admin_form())
		{
			$this->ipsclass->html .= $html;
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Edit Scratchcard");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_scratchcard_edit_save()
	{
		$this->ipsclass->input['card'] = intval($this->ipsclass->input['card']);
		
		if(!is_array($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]))
		{
			$this->ipsclass->admin->error("Unknown scratchcard");
		}
		
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]);
		
		$card = array(
						'name' => $this->ipsclass->input['name'],
						'description' => $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->han_editor->process_raw_post( 'description' ) ) ),
						'price' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['price'],'int'),
						'prizes' => array(),
					);
		
		$class->admin_save($card);
		
		$card['prizes'] = serialize($card['prizes']);
		$card['description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $card['description'] ) );
		
		$this->ipsclass->DB->do_update('market_scratchcard_card',$card,"sc_id=".$this->ipsclass->input['card']);
		
		$this->scratchcard_cache();
		
		$this->ipsclass->admin->save_log("ibMarket: Scratchcard Edited");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Scratchcard edited...");
	}
	
	function acp_scratchcard_delete()
	{
		$this->ipsclass->input['card'] = intval($this->ipsclass->input['card']);
		
		if(!is_array($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]))
		{
			$this->ipsclass->admin->error("Unknown scratchcard");
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_scratchcard_card','where'=>"sc_id=".$this->ipsclass->input['card']));
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_scratchcard_ticket','where'=>"card_id=".$this->ipsclass->input['card']));
		
		$this->scratchcard_cache();
		
		$this->ipsclass->admin->save_log("ibMarket: Scratchcard Deleted");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Scratchcard deleted...");
	}
	
	function acp_scratchcard_export()
	{
		if(!is_array($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]))
		{
			$this->ipsclass->error("Invalid scratchcard");
		}
		
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]);
		
		require_once( KERNEL_PATH.'class_xml.php' );
		$xml = new class_xml();
		
		$xml->xml_set_root('scratchcardexport',array('exported'=>time()));
		$xml->xml_add_group('scratchcard');
		$entry = array();
		$content = array();
		$content[] = $xml->xml_build_simple_tag('folder',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['folder']);
		$content[] = $xml->xml_build_simple_tag('size_width',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['size_width']);
		$content[] = $xml->xml_build_simple_tag('size_height',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['size_height']);
		$content[] = $xml->xml_build_simple_tag('card_img',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['card_img']);
		$content[] = $xml->xml_build_simple_tag('empty_img',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['empty_img']);
		$content[] = $xml->xml_build_simple_tag('game_type',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['game_type']);
		$content[] = $xml->xml_build_simple_tag('name',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['name']);
		$content[] = $xml->xml_build_simple_tag('description',$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['description']);
		$entry[] = $xml->xml_build_entry('card_info',$content);
		$xml->xml_add_entry_to_group('scratchcard',$entry);
		$xml->xml_add_group('image_files');
		$entry = array();
		foreach($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['choice_imgs'] as $img_file)
		{
			$content = array();
			$content[] = $xml->xml_build_simple_tag('file',$img_file);
			$entry[] = $xml->xml_build_entry('image',$content);
		}
		$xml->xml_add_entry_to_group('image_files',$entry);
		$xml->xml_add_group('image_location');
		$entry = array();
		foreach($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['choice_info'] as $location)
		{
			$content = array();
			$content[] = $xml->xml_build_simple_tag('top',$location['top']);
			$content[] = $xml->xml_build_simple_tag('left',$location['left']);
			$content[] = $xml->xml_build_simple_tag('width',$location['width']);
			$content[] = $xml->xml_build_simple_tag('height',$location['height']);
			$entry[] = $xml->xml_build_entry('location',$content);
		}
		$xml->xml_add_entry_to_group('image_location',$entry);
		
		$class->export($xml);
		
		$xml->xml_format_document();
		
		$this->ipsclass->admin->show_download( $xml->xml_document, $this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['folder'].".xml", "unknown/unknown" , 0 );
	}
	
	function acp_view_ticket()
	{
		// Yes redirect again >_>
		$redirect = array(
								'list' => 'list',
								'display' => 'display',
							);
		if(!$redirect[$this->ipsclass->input['runme']])
		{
			$this->ipsclass->input['runme'] = 'list';
		}
		
		$function = 'acp_ticket_'.$redirect[$this->ipsclass->input['runme']];
		$this->$function();
	}
	
	function acp_ticket_list()
	{
		$LIMIT = 50;
		
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$this->ipsclass->admin->page_title  = "Welcome to ticket page for scratchcards";
		$this->ipsclass->admin->page_detail = "Welcome to ticket page for any scratchcard.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=ticket', 'Scratchcard Tickets' );
		
		$this->ipsclass->html .= "<script type=\"text/javascript\">
function display_ticket(id,x,y)
{
	window.open(\"{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=ticket&runme=display&ticket=\" + id, \"\", \"scrollbars=no,address=no,toolbar=no,status=yes,width=\" + x + \",height=\" + y);
}
</script>";
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_scratchcard_ticket'));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=ticket"
															)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Member"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Card"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "Bought"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Status"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Win/Lose" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Tickets");
		
		$this->ipsclass->DB->build_query(array(
													'select' => 't.*',
													'from' => array('market_scratchcard_ticket'=>'t'),
													'add_join' => array(
																			array(
																					'select' => 'm.members_display_name, m.mgroup',
																					'from' => array('members'=>'m'),
																					'where' => 'm.id=t.member_id',
																					'type' => 'left',
																				),
																		),
													'order' => 'time_created DESC',
													'limit' => array($this->ipsclass->input['st'],$LIMIT)
										)		);
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array(  $this->ipsclass->market_admin->format_name($ticket['member_id'],$ticket['members_display_name'],$ticket['mgroup']),
																				  $this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['name'],
																				  $this->ipsclass->get_date($ticket['time_created'],'LONG'),
																				  "<a href=\"javascript:void(0);\" onclick=\"display_ticket({$ticket['tick_id']},{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['size_width']},{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['size_height']});\">".($ticket['used'] == 0 ? "Unfinished" : "Used")."</a>",
																				  $ticket['won'] == 0 ? "Lose" : "Won",
																		 )      );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_ticket_display()
	{
		$ticket = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_scratchcard_ticket','where'=>"tick_id=".$this->ipsclass->input['ticket']));
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]);
		
		$display = <<<EOF
<html>
	<head>
		<title>
			{$this->plugin['name']} - {$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['name']}
		</title>
	</head>
	<body bgcolor='#ffffff' topmargin='0' leftmargin='0' rightmargin='0' bottommargin='0' style='margin:0px;background-color:#ffffff;'>
		<img src='{$this->ipsclass->market_class->image_url_path}/scratchcard/{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['folder']}/{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['card_img']}' border='0' width='{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['size_width']}' height='{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['size_height']}' alt='{$this->ipsclass->cache['market_plugin'][$this->ipsclass->input['plugin']]['name']}' />

EOF;
		
		$ticket['choices'] = unserialize($ticket['choices']);
		$ticket['seen'] = unserialize($ticket['seen']);
		
		foreach($this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['choice_info'] as $l_id => $location)
		{
			$display .= <<<EOF
		<div style='position: absolute; top: {$location['top']}; left: {$location['left']};width: {$location['width']}; height: {$location['height']}'>

EOF;
			if($ticket['seen'][$l_id])
			{
				$display .= <<<EOF
			<img src='{$this->ipsclass->market_class->image_url_path}/scratchcard/{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['folder']}/{$ticket['choices'][$l_id]}' border='0' width='{$location['width']}' height='{$location['height']}' />

EOF;
			}
			elseif($this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['empty_img'])
			{
				$display .= <<<EOF
			<img src='{$this->ipsclass->market_class->image_url_path}/scratchcard/{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['folder']}/{$this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]['empty_img']}' border='0' width='{$location['width']}' height='{$location['height']}' />

EOF;
			}
			else
			{
				$display .= <<<EOF
			<img src='{$this->ipsclass->market_class->image_url_path}/scratchcard/blank.png' border='0' width='{$location['width']}' height='{$location['height']}' />

EOF;
			}
			$display .= <<<EOF
		</div>

EOF;
		}
		
		$display .= $class->display_ticket($ticket);
		
		$display .= <<<EOF
	</body>
</html>
EOF;
		
		print $display;
		exit();
	}
	
	function run()
	{
		$this->ipsclass->load_template('skin_market_plugin');
		$this->ipsclass->load_language('lang_market_plugin');
		
		if(in_array($this->ipsclass->member['mgroup'],$this->plugin['use_permission']))
		{
			$do_redirect = array(
									'card' => 'card_list',
									'display' => 'display_ticket',
									'ticket' => 'create_ticket',
									'play' => 'uncover_area',
									'result' => 'ticket_result',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'card';
			}
		}
		else
		{
			$this->ipsclass->market_class->menu[] = array(
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}&amp;do=create'>".$this->ipsclass->lang['scratchcard_scratchcards']."</a></b>",
														);
			
			$do_redirect = array(
									'card' => 'card_list',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'card';
			}
		}
		
		$func = 'run_'.$do_redirect[$this->ipsclass->input['do']];
		$this->$func();
	}
	
	function run_card_list()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['scratchcard_scratchcards'];
		$this->ipsclass->nav = array("<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->ipsclass->input['plugin']}&amp;do=create'>".$this->ipsclass->lang['scratchcard_scratchcards']."</a></b>");
		
		foreach(array_keys($this->ipsclass->cache['ibm_scratchcard']) as $s_id)
		{
			$this->ipsclass->cache['ibm_scratchcard'][$s_id]['price'] = $this->ipsclass->numbers->multiply($this->ipsclass->cache['ibm_scratchcard'][$s_id]['price'],$this->ipsclass->member['market_deduct']);
			$this->ipsclass->cache['ibm_scratchcard'][$s_id]['price'] = $this->ipsclass->numbers->format_currency($this->ipsclass->cache['ibm_scratchcard'][$s_id]['price']);
		}
		
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$LIMIT = 10;
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_scratchcard_ticket','where'=>"member_id=".$this->ipsclass->member['id']));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin'],0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin'],
																'USE_ST'       => 'st',
														)	);
		
		$tickets = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_scratchcard_ticket','where'=>"member_id=".$this->ipsclass->member['id'],'order'=>"used ASC, time_created DESC",'limit'=>array($this->ipsclass->input['st'],$LIMIT)));
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$ticket['time_created'] = $this->ipsclass->get_date($ticket['time_created'],'TINY');
			$tickets[] = $ticket;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->scratchcard_main_page($tickets,$page_links);
	}
	
	function mini_error($lang="")
	{
		print $this->ipsclass->compiled_templates['skin_market_plugin']->scratchcard_ticket_error($this->ipsclass->lang[$lang]);
		exit();
	}
	
	function run_display_ticket()
	{
		$this->ipsclass->input['ticket'] = intval($this->ipsclass->input['ticket']);
		$ticket = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_scratchcard_ticket','where'=>"tick_id=".$this->ipsclass->input['ticket']));
		if($ticket['member_id'] != $this->ipsclass->member['id'])
		{
			$this->mini_error('scratchcard_unknown');
		}
		$ticket['choices'] = unserialize($ticket['choices']);
		$ticket['seen'] = unserialize($ticket['seen']);
		
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]);
		
		print $this->ipsclass->compiled_templates['skin_market_plugin']->scratchcard_display_ticket($ticket,$class->display_ticket($ticket));
		exit();
	}
	
	function run_create_ticket()
	{
		$this->ipsclass->input['card'] = intval($this->ipsclass->input['card']);
		if(!is_array($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]))
		{
			$this->mini_error('scratchcard_unknown');
		}
		
		$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['price'] = $this->ipsclass->numbers->multiply($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['price'],$this->ipsclass->member['market_deduct']);
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['price'],$this->ipsclass->member[$this->ipsclass->vars['market_members_field']]) > 0)
		{
			$this->mini_error('scratchcard_not_enough_money');
		}
		
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]['price']),
				),"id=".$this->ipsclass->member['id']);
		
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$this->ipsclass->input['card']]);
		$ticket = array();
		$ticket['card_id'] = $this->ipsclass->input['card'];
		$ticket['time_created'] = time();
		$ticket['member_id'] = $this->ipsclass->member['id'];
		$ticket['won'] = $class->is_going_to_win();
		$ticket['choices'] = serialize($class->create_choices($ticket['won']));
		$ticket['seen'] = array();
		foreach(array_keys($class->card_info['choice_info']) as $l)
		{
			$ticket['seen'][$l] = 0;
		}
		$ticket['seen'] = serialize($ticket['seen']);
		$ticket['used'] = 0;
		$ticket['ip_address'] = $this->ipsclass->ip_address;
		$class->create_ticket($ticket);
		$this->ipsclass->DB->do_insert('market_scratchcard_ticket',$ticket);
		
		$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=display&amp;ticket=".$this->ipsclass->DB->get_insert_id());
	}
	
	function run_uncover_area()
	{
		$this->ipsclass->input['ticket'] = intval($this->ipsclass->input['ticket']);
		$this->ipsclass->input['area'] = intval($this->ipsclass->input['area']);
		$ticket = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_scratchcard_ticket','where'=>"tick_id=".$this->ipsclass->input['ticket']));
		if($ticket['member_id'] != $this->ipsclass->member['id'])
		{
			$this->mini_error('scratchcard_unknown');
		}
		if($ticket['used'])
		{
			$this->mini_error('scratchcard_unknown');
		}
		$ticket['seen'] = unserialize($ticket['seen']);
		$ticket['seen'][$this->ipsclass->input['area']] = 1;
		$this->ipsclass->DB->do_update('market_scratchcard_ticket',array('seen'=>serialize($ticket['seen'])),"tick_id=".$this->ipsclass->input['ticket']);
		
		$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=display&amp;ticket=".$this->ipsclass->input['ticket']);
	}
	
	function run_ticket_result()
	{
		$this->ipsclass->input['ticket'] = intval($this->ipsclass->input['ticket']);
		$ticket = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_scratchcard_ticket','where'=>"tick_id=".$this->ipsclass->input['ticket']));
		if($ticket['member_id'] != $this->ipsclass->member['id'])
		{
			$this->mini_error('scratchcard_unknown');
		}
		$class = $this->load_gametype($this->ipsclass->cache['ibm_scratchcard'][$ticket['card_id']]);
		if(!$ticket['used'])
		{
			$this->ipsclass->DB->do_update('market_scratchcard_ticket',array('used'=>1),"tick_id=".$this->ipsclass->input['ticket']);
			
			if($ticket['won'])
			{
				if($money = $class->money_reward($ticket['won']))
				{
					$this->ipsclass->DB->do_update('members',array(
																	$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->add($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$money),
							),"id=".$this->ipsclass->member['id']);
				}
				$items = $class->items_reward($ticket['won']);
				if(is_array($items) && count($items))
				{
					$time = time();
					foreach($items as $item_id => $quanity)
					{
						$expired = $this->ipsclass->cache['market_items'][$item_id]['expire_time'] > 0 ? $time + $this->ipsclass->cache['market_items'][$item_id]['expire_time'] * $this->ipsclass->cache['market_items'][$item_id]['expire_unit'] : 0;
						for($i = 0; $i < $quanity; $i++)
						{
							$this->ipsclass->DB->do_insert('market_inventory',array(
																						'member_id' => $this->ipsclass->member['id'],
																						'item' => $item_id,
																						'price_bought' => $this->ipsclass->cache['market_items'][$item_id]['price'],
																						'resell_price' => $this->ipsclass->cache['market_items'][$item_id]['resell'],
																						'time_bought' => $time,
																						'expired' => $expired,
															)						);
						}
					}
				}
			}
		}
		
		$msg = "";
		if($ticket['won'])
		{
			$msg = $this->ipsclass->lang['scratchcard_you_won'];
		}
		else
		{
			$msg = $this->ipsclass->lang['scratchcard_you_lose'];
		}
		
		print $this->ipsclass->compiled_templates['skin_market_plugin']->scratchcard_ticket_result($msg);
		exit();
	}
	
	function xml_old_tickets()
	{
		
	}
}
?>